package pay

import (
	"context"
	"github.com/gin-gonic/gin"
	"github.com/smartwalle/alipay/v3"
	"go.uber.org/zap"
	"net/http"
	"shop_webs/order_web/global"
	"shop_webs/order_web/proto"
)

func Notify(ctx *gin.Context) {
	alipayCfg := global.ServerConfig.Alipay
	//生成支付宝的支付url
	client, err := alipay.New(alipayCfg.AppID, alipayCfg.PrivateKey, false)
	if err != nil {
		zap.S().Errorw("实例化支付宝失败")
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"msg": err.Error(),
		})
		return
	}
	err = client.LoadAliPayPublicKey(alipayCfg.AliPublicKey)
	if err != nil {
		zap.S().Errorw("加载支付宝的公钥失败")
		ctx.JSON(http.StatusNotFound, gin.H{
			"msg": err.Error(),
		})
		return
	}

	notify, err := client.GetTradeNotification(ctx.Request) //这个会自动验证签名是否正确
	if err != nil {
		zap.S().Info("交易失败：", err)
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"msg": err.Error(),
		})
		return
	}
	//修改订单状态为已支付
	_, err = global.OrderClient.UpdateOrderStatus(context.Background(), &proto.OrderStatus{
		OrderSn: notify.OutTradeNo, // 商户订单号，这个是我们自己生成的订单号
		Status:  string(notify.TradeStatus),
	})
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"msg": err.Error(),
		})
		return
	}
	//alipay.ACKNotification(writer)		看源码
	ctx.String(http.StatusOK, "success")
}
